<!--
 * @Descripttion: 
 * @version: 
 * @Author: dudu
 * @Date: 2020-02-27 09:03:15
 * @LastEditors: dudu
 * @LastEditTime: 2020-02-27 09:58:20
 -->
<template>
  <div>
    <el-popover placement="top"
                width="160"
                v-model="visible"
                @hide="handleConfirmColumnFilter">
      <el-table ref="multipleTable"
                :data="originHeaders"
                size="mini"
                border
                @selection-change="handleSelectionChange">
        <el-table-column type="selection"
                         :selectable="row => !row.disabled">
        </el-table-column>
        <el-table-column prop="label"
                         label="列名"> </el-table-column>
      </el-table>
      <el-button slot="reference">触发列筛选</el-button>
    </el-popover>
  </div>
</template>

<script>
export default {
  props: {
    tableData: {},
    tableHeaders: {},
  },

  data () {
    return {
      visible: false, //筛选列可见性
      selectedColumns: [], //维护当前选中项
      originData: [],//原始表数据
      originHeaders: []//原始列数据
    };
  },
  methods: {
    //   更改选中列
    handleSelectionChange (list) {
      this.selectedColumns = [...list];
    },
    // 隐藏时触发列筛选更新
    handleConfirmColumnFilter () {
      this.visible = false;
      const columns = this.selectedColumns.map(column => column.name);
      this.$emit(
        "update:tableData",
        this.originData.map(row => {
          return _.pick(row, columns);
        })
      );
      this.$emit(
        "update:tableHeaders",
        this.originHeaders.filter(column => {
          return columns.includes(column.name);
        })
      );
      this.$emit("update", this.selectedColumns);
    },
    // 设定指定行选中
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    }
  },
  mounted () {
    //   初始化赋值列、表数据
    this.originData = _.cloneDeep(this.tableData);
    this.originHeaders = _.cloneDeep(this.tableHeaders);
    this.$nextTick(_ => {
      // 设定全部列默认选中
      this.toggleSelection(this.originHeaders);
    })
  }
};
</script>

<style></style>
